package com.molyfun.core.interceptor;

import java.util.Map;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.molyfun.core.annotation.Authorization;
import com.molyfun.core.support.HoUserService;
import com.molyfun.core.support.HttpCode;
import com.molyfun.core.util.WebUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.method.HandlerMethod;

import java.io.IOException;
import java.lang.reflect.Method;

/**
 * 权限拦截器
 * 
 */
public class AuthInterceptor extends BaseInterceptor {

	@Autowired
	public HoUserService userService;

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		//从header中取出验证信息
		Map<String,String> headers = WebUtil.getHeadersInfo(request);
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		Method method = handlerMethod.getMethod();

		//方法上注解了Authorization,表示该方法需要token验证
		if (method.getAnnotation(Authorization.class) != null) {
			String token = headers.get("token");
			if(StringUtils.isEmpty(token))
			{
				ResponseResult(HttpCode.BUSINESS_FAIL.value(),"token参数缺失",response);
				return false;
			}

			String userId = this.userService.queryUserIdByToken(token);
			if(StringUtils.isEmpty(userId))
			{
				ResponseResult(HttpCode.BUSINESS_FAIL.value(),"token验证失败,请重新登陆",response);
				return false;
			}
			request.setAttribute("userId", userId);
			return true;
		}
		return super.preHandle(request, response, handler);
	}

	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		super.afterCompletion(request, response, handler, ex);
	}

	public void ResponseResult(Integer code,String msg,HttpServletResponse response) throws IOException
	{
		//	验证token
		ModelMap modelMap = new ModelMap();
		modelMap.put("code", code);
		modelMap.put("msg", msg);
		response.setContentType("application/json;charset=UTF-8");
		byte[] bytes = JSON.toJSONBytes(modelMap, SerializerFeature.DisableCircularReferenceDetect);
		response.getOutputStream().write(bytes);
	}
}
